require "import"
import "android.app.*"
import "android.os.*"
import "android.widget.*"
import "android.view.*"
import "layout"
activity.setTitle("Manalua+")
activity.setTheme(android.R.style.Theme_Material_Light_NoActionBar)
activity.setContentView(loadlayout(layout))

import "java.io.FileInputStream"
import "java.io.FileOutputStream"
import "java.io.BufferedOutputStream"
import "java.io.ByteArrayOutputStream"
import "java.io.BufferedInputStream"

import "java.nio.ByteBuffer"
import "java.nio.ByteOrder"

import "java.util.zip.ZipFile"
import "java.util.zip.ZipInputStream"
import "java.util.zip.ZipOutputStream"

local path = "/sdcard/kk.mpkg"--MPKG转ZIP输入
local out = "/sdcard/kk.zip"--MPKG转ZIP输出
local fis = FileInputStream(path)
local zos = ZipOutputStream(FileOutputStream(out))
local bit = require "bit32"

function readInt()
    local bytes = byte[4]
    fis.read(bytes)
    return (bytes[0] & 0xFF) | ((bytes[1] << 8) & 0xFFFF) | (bit.rshift(bytes[2] << 24, 8)) | (bytes[3] << 24)
end

function readData(length)
    local bytes = byte[length]
    fis.read(bytes)
    return bytes
end

-- 版本号
local ver = String(readData(readInt()))
zos.setComment(ver)
local filenum = readInt()
local dataTable = {}
local lengthTable = {}
for i = 1, filenum do
    dataTable[i] = String(readData(readInt()))
    readInt() -- 跳过index
    lengthTable[i] = readInt()
end

import "java.util.zip.ZipEntry"
for i = 1, #dataTable do
    zos.putNextEntry(ZipEntry(dataTable[i]))
    zos.write(readData(lengthTable[i]))
    zos.closeEntry()
end
fis.close()
zos.close()
print("转换完成: mpkg -> zip")

-- 反向转换
local zf = ZipFile(out)
local ver = zf.getComment()
local filenum = zf.size()
local zis = ZipInputStream(FileInputStream(out))
local ze = zis.getNextEntry()
local index = 0
local fos = FileOutputStream("/sdcard/kk1.mpkg")--ZIP转MPKG输出


function writeInt(i)
    local bytes = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(i).array()
    fos.write(bytes)
end

function writeData(bytes)
    fos.write(bytes)
end

function writeStr(str)
    writeData(String(str).getBytes())
end

writeInt(#ver)
writeStr(ver)
writeInt(filenum)

local baos = ByteArrayOutputStream()
local entries = zf.entries()

while entries.hasMoreElements() do
    local ze = entries.nextElement()
    local bis = BufferedInputStream(zf.getInputStream(ze))
    local length = bis.available()
    local name = ze.getName()
    
    writeInt(#name)
    writeStr(name)
    writeInt(index)
    writeInt(length)
    
    index = index + length
    
    local bytes = byte[length]
    bis.read(bytes)
    baos.write(bytes)
    bis.close()
end

zf.close()
writeData(baos.toByteArray())
fos.close()
zis.close()
print("转换完成: zip -> mpkg")